package m202401.d03;

import java.util.*;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/1/3 09:17
 */
//56. 合并区间
public class Q56 {

    public static void main(String[] args) {
        Q56 q56 = new Q56();
        int[][] merge = q56.merge(new int[][]{
                {1, 3}, {2, 6}, {8, 10}, {15, 18}
        });
        System.out.println();
    }

    public int[][] merge(int[][] intervals) {

        Arrays.sort(intervals, Comparator.comparingInt(o -> o[0]));

        List<int[]> list = new ArrayList<>();

        int min = intervals[0][0];
        int max = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            int[] interval = intervals[i];
            if (interval[0] <= max) {
                max = Math.max(interval[1], max);
            } else {
                list.add(new int[]{min, max});
                min = interval[0];
                max = interval[1];
            }
        }
        list.add(new int[]{min, max});
        return list.toArray(new int[list.size()][]);
    }
}
